//
//  YYSliderCaptchaView.m
//  SHWheel
//
//  Created by YYKJ on 2020/8/4.
//  Copyright © 2020 YYKJ. All rights reserved.
//

#import "YYSliderCaptchaView.h"
#import "SHCommonDefines.h"
#import "UIBezierPath+DWPathUtils.h"
#import "DWSlideCaptchaView.h"
#import "UIImage+DWImageUtils.h"
#import "DWMacro.h"
#import "UIColor+YY.h"
#import "UIView+YY.h"

@interface ZGCaptchaSlider ()

@end

@implementation ZGCaptchaSlider
// lets a subclass lay out the track and thumb as needed

- (CGRect)trackRectForBounds:(CGRect)bounds {
    CGRect rect = [super trackRectForBounds:bounds];
//    NSLog(@"trackRect = %@", NSStringFromCGRect(rect));
    return rect;
}

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {
//    NSLog(@"thumbRect = %@", NSStringFromCGRect(thumbRect));
    rect.origin.x = rect.origin.x - 16;
    rect.size.width = rect.size.width + 32;
    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value];
    return CGRectInset(thumbRect, 16, 16);
}

@end

@implementation ZGSliderCapchaView

- (void)beginConfiguration {
    
}

- (void)commitConfiguration {
    
}



@end


@interface YYSliderCaptchaView () <DWSlideCaptchaDelegate>
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UILabel *sliderLabel;
@property (nonatomic, strong) UIImage *verificationImage;

@end

@implementation YYSliderCaptchaView

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"slider.tracking"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image {
    self = [super initWithFrame:frame];
    if (self) {
        [self xx_drawShadowRadius:9.0];
        
        _slider = [[ZGCaptchaSlider alloc] initWithFrame:CGRectMake(12, frame.size.height - 32 - 12, frame.size.width - 2 * 12, 32)];
        [_slider setThumbImage:[UIImage imageNamed:@"slidebutton"] forState:UIControlStateNormal];
        _slider.backgroundColor = [UIColor colorWithHexString:@"F2F2F2"];
        _slider.minimumTrackTintColor = UIColor.clearColor;
        _slider.maximumTrackTintColor = UIColor.clearColor;
        _slider.layer.cornerRadius = CGRectGetHeight(_slider.bounds) / 2;
        
        UILabel *label = [[UILabel alloc] initWithFrame:_slider.bounds];
        label.x += 10;
        label.text = @"拖动左边滑块完成上方拼图";
        label.textColor = [UIColor colorWithHexString:@"999999"];
        label.font = [UIFont systemFontOfSize:12];
        label.textAlignment = NSTextAlignmentCenter;
        label.userInteractionEnabled = NO;
        [_slider addSubview: label];
        self.sliderLabel = label;
        [_slider addTarget:self action:@selector(sliderValueChange) forControlEvents:(UIControlEventValueChanged)];
        
        _captchaView = [[DWSlideCaptchaView alloc] initWithFrame:CGRectMakeWithPointAndSize(CGPointZero, CGSizeMake(frame.size.width, 142)) bgImage:image];
        [_captchaView xx_drawCornerRadius:9.0 byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight];
        _captchaView.delegate = self;
        
        // refresh button
        UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [refreshButton setImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
        [self addSubview:refreshButton];
        refreshButton.frame = CGRectMake(_captchaView.width - 40, _captchaView.maxY, 40, 40);
        [refreshButton addTarget:self action:@selector(refreshButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        // delete button
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [deleteButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        [self addSubview:deleteButton];
        deleteButton.frame = CGRectMake(_captchaView.width - 2*40 , _captchaView.maxY, 40, 40);
        [deleteButton addTarget:self action:@selector(deleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview:_slider];
        [self addSubview:_captchaView];
        
        ///为了获取slider结束拖动使用KVO
        [self addObserver:self forKeyPath:@"slider.tracking" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
        
        ///为了改变验证视图的时使用通知观察slider的数值
        [self.slider addTarget:self action:@selector(sliderValueChange) forControlEvents:(UIControlEventValueChanged)];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"slider.tracking"]) {
        if ([change[@"new"] integerValue] == 0 && [change[@"old"] integerValue] == 1) {///silder结束拖动，开始验证
            if (!self.captchaView.isSuccessed) {
                [self.captchaView indentifyWithAnimated:YES result:^(BOOL success) {
                    
                    if (!success) {
                        [self refresh];
                    } else {
                        [self dismissWithCompletion:nil];
                    }
                    
                    if (self.identifierCheckCompletion) {
                        self.identifierCheckCompletion(success);
                    }
                }];
            }
        } else if ([change[@"new"] integerValue] == 0 && [change[@"old"] integerValue] == 0) {///slider归位
            if (self.slider.value) {
                self.slider.value = 0;
            }
        }
    }
}

- (void)sliderValueChange {
    if (!self.captchaView.isIndentified) {
        [self.captchaView setValue:self.slider.value animated:NO];
    }
    
    if (self.slider.value == 0) {
        self.sliderLabel.alpha = 1;
    } else {
        [UIView animateWithDuration:0.25 animations:^{
            self.sliderLabel.alpha = 0;
        }];
    }
}

- (void)dw_CaptchaView:(DWSlideCaptchaView *)captchaView animationCompletionWithSuccess:(BOOL)success {
    if (!success) {
        [self.captchaView setValue:0 animated:YES];
        [self.captchaView hideThumbWithAnimated:YES];
    }
}

/// 刷新页面，重新验证
- (void)refresh {
    [self refreshButtonClick:nil];
}

- (void)showAnimation:(BOOL)animation {
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    UIView *bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    bgView.backgroundColor = UIColor.clearColor;
    [[UIApplication sharedApplication].keyWindow addSubview:bgView];
    [bgView addSubview:self];
    self.bgView = bgView;
    
    self.alpha = 0;
    NSTimeInterval duration = animation ? 0.25 : 0.00;
    [UIView animateWithDuration:duration animations:^{
        self.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)dismissWithCompletion:(void(^)(BOOL isSuccess))completion {
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        [self.bgView removeFromSuperview];
    }];
}

#pragma mark - Event response
- (void)bgClick:(UIGestureRecognizer *)tap {
    [self dismissWithCompletion:^(BOOL isSuccess) {
        
    }];
}

- (void)refreshButtonClick:(UIButton *)sender {
    // 替换图片
    [_captchaView beginConfiguration];
    _captchaView.bgImage = [UIImage imageNamed:@"picture1"];
    [_captchaView commitConfiguration];
}

- (void)deleteButtonClick:(UIButton *)sender {
    [self dismissWithCompletion:^(BOOL isSuccess) {
        
    }];
}

@end
